#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://www.scadacore.com/tools/programming-calculators/online-hex-converter/

import codecs
import binascii
import re
import struct


def str2Bytes(st: str):
    clear_st = re.sub("[^0-9a-fA-F]", "", st)
    if len(clear_st) % 2 == 1:
        clear_st = clear_st[:-1] + "0" + clear_st[-1]
    result_bytes = binascii.a2b_hex(clear_st)
    return result_bytes


def bytesPuttyPrint(b: bytes):
    st = codecs.encode(b, "hex").decode("utf-8").upper()
    it = iter(st)
    result_str = " ".join(a + b for a, b in zip(it, it))
    return result_str


def bytes2Int(b: bytes, index: int = 0, length: int = 0, signed=False):
    if index == 0 and length == 0:
        return int.from_bytes(b, byteorder="big", signed=signed)
    else:
        return int.from_bytes(b[index : index + length], byteorder="big", signed=signed)


def bytes2Float32(b: bytes, module: str = "DCBA"):
    """
        Float - Big Endian (ABCD)
        Float - Little Endian (DCBA)
        Float - Mid-Big Endian (BADC)
        Float - Mid-Little Endian (CDAB)
        print(struct.unpack('f', b'\x12\x34\x56\x78')) # DCBA
        print(struct.unpack('f', b'\x34\x12\x78\x56')) # CDAB
        print(struct.unpack('f', b'\x56\x78\x12\x34')) # BADC
        print(struct.unpack('f', b'\x78\x56\x34\x12')) # ABCD
    """
    if len(b) != 4:
        return None
    moduleList = ("DCBA", "CDAB", "BADC", "ABCD")
    if module not in moduleList:
        idx = 0
    else:
        idx = moduleList.index(module)
    if idx == 0:
        return struct.unpack("f", b)[0]
    elif idx == 1:
        return struct.unpack("f", b"".join((b[1:2], b[0:1], b[3:4], b[2:3])))[0]
    elif idx == 2:
        return struct.unpack("f", b"".join((b[2:3], b[3:4], b[0:1], b[1:2])))[0]
    elif idx == 3:
        return struct.unpack("f", b"".join((b[3:4], b[2:3], b[1:2], b[0:1])))[0]


def getChineseStringLength(data):
    count = 0
    for s in data:
        if ord(s) > 127:
            count += 1
    return count


def iecDateTimeStr(data: int):
    """时间数据解析 int-->str"""
    year = data[0]
    month, day = data[1] // 256, data[1] % 256
    hour, minute = data[2] // 256, data[2] % 256
    second, microSecond = data[3] // 1000, data[3] % 1000
    return "{}{:02d}{:02d} {:02d}:{:02d}:{:02d}.{:03d}".format(year, month, day, hour, minute, second, microSecond)
